package com.chaoyer.cynet.common.utils;

import io.netty.handler.codec.http.multipart.FileUpload;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;


/**
 * 文件 工具类
 */
public class FileUtils {

    /**
     * 保存文件
     *
     * @param dest       文件存放地址 已存在则替代掉
     * @param fileUpload netty FileUpload对象
     */
    public static void saveFile(String dest, FileUpload fileUpload) throws IOException {
        File file = new File(dest);
        fileUpload.renameTo(file);
    }


    /**
     * 文件的md5值
     *
     * @param file 文件
     * @return 文件md5
     */
    public static String md5File(File file) throws FileNotFoundException {
        String value = null;
        FileInputStream in = new FileInputStream(file);
        try {
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return value;
    }

    /**
     * 判断文件是否是图片
     *
     * @param file 文件
     * @return 是否是图片
     */
    public static boolean isImage(File file) throws IOException {
        return ImageIO.read(file) != null;
    }
}
